package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 李旭
 * @date 2022/1/8 15:02
 * @Description:
 */
@Service
public class TestServiceImpl implements TestService {

    //private final Lock lock = new ReentrantLock();//JUC 包下本地锁  新

    @Autowired
    private RedisTemplate redisTemplate;


    //使用 apache ab压力测试工具  压力测试  5000个请求  同时并发100
    @Override
    public void testLock() {
    /*    lock.lock();
        try {
            Integer num = (Integer) redisTemplate.opsForValue().get("num");
            num++;
            redisTemplate.opsForValue().set("num",num);
        } finally {
            lock.unlock();
        }*/
        //分布式锁
        String uuid = UUID.randomUUID().toString();
        //1:先加锁  setnx    java:setIfAbsent
        Boolean isLock = redisTemplate.opsForValue().setIfAbsent("state", uuid,
                            1, TimeUnit.SECONDS);
        if(isLock){
            //获取到了锁
            try {
                Integer num = (Integer) redisTemplate.opsForValue().get("num");//不见不散的
                num++;
                redisTemplate.opsForValue().set("num",num);
            } finally {
                //解锁  防误删
           /*     if(uuid.equals(redisTemplate.opsForValue().get("state"))){
                    //是我的锁
                    redisTemplate.delete("state");
                }*/
                //LUA脚本
                // 2. 释放锁 del
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
                //执行上面的LUA脚本
                this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList("state"), uuid);
            }
        }else{
            //未获取到锁
            testLock();
        }

    }
}
